package middleware

import (
	"admin-system/internal/util"
	"admin-system/pkg/error_code"
	"admin-system/pkg/response"
	"github.com/gin-gonic/gin"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取authorization header
		tokenReq := c.Request.Header.Get("Authorization")
		if tokenReq == "" || !strings.HasPrefix(tokenReq, "Bearer ") {
			response.Fail(c, error_code.ErrTokenInvalid, "token 不合法")
			c.Abort() // 停止请求
			return
		}
		// 验证 token 的格式
		token := tokenReq[7:] // 去掉Bearer前缀

		// 解析 token
		claims, err := util.ParseToken(token)
		if err != nil {
			response.Fail(c, error_code.ErrTokenInvalid, "token 无效")
			c.Abort()
			return
		}
		// 用户信息存入context
		c.Set("user_id", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("role_id", claims.RoleID)
		c.Next()
	}
}
